r"""
请完成一个函数，输入一个二叉树，该函数输出它的镜像。

例如输入：

     4
   /   \
  2     7
 / \   / \
1   3 6   9
镜像输出：

     4
   /   \
  7     2
 / \   / \
9   6 3   1

 

示例 1：
输入：root = [4,2,7,1,3,6,9]
输出：[4,7,2,9,6,3,1]
 

限制：
0 <= 节点个数 <= 1000

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
"""
from examples.二叉树的层序遍历 import Solution as S


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

    def __repr__(self):
        s = S()
        return str(s.level_order(self))

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return root

        def switch(left: TreeNode, right: TreeNode):
            left, right = right, left
            if left:
                left.left, left.right = switch(left.left, left.right)
            if right:
                right.right, right.left = switch(right.right, right.left)
            return left, right

        root.left, root.right = switch(root.left, root.right)
        return root

    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return root
        root.left, root.right = root.right, root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root


if __name__ == '__main__':
    tree = TreeNode(4)
    tree.left = TreeNode(2)
    tree.right = TreeNode(7)
    tree.left.left = TreeNode(1)
    tree.left.right = TreeNode(3)
    tree.right.left = TreeNode(6)
    tree.right.right = TreeNode(9)
    print(tree)
    s = Solution()
    # print(s.mirrorTree(tree))
    tree1 = TreeNode(1)
    tree1.left = TreeNode(4)
    tree1.right = TreeNode(3)
    tree1.left.left = TreeNode(2)
    print(tree1)
    print(s.mirrorTree(tree1))
    print(tree1)
    print(s.invertTree(tree1))
